import * as React from "react";
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Linking
} from "react-native";
import { ListItem, Avatar } from "react-native-elements";
import { LargeList } from "react-native-largelist-v3";
import {
  ChineseWithLastDateHeader,
  ChineseWithLastDateFooter
} from "react-native-spring-scrollview";
import Icon from "react-native-vector-icons/FontAwesome";
import RNToast from "./View/ShowToast";

import SearchView from "./View/SearchView";

import { observer, inject } from "mobx-react";

import Network from "./Service/Network";
import SearchStore from "./Model/SearchStore";

interface Props extends React.Props<any> {
  navigation: any;
  searchStore: SearchStore;
}

interface State {
  allLoaded: boolean;
  list: Array<any>;
  srcList: Array<any>;
}

@inject("searchStore")
@observer
export default class Home extends React.Component<Props, State> {
  static navigationOptions: any = {
    title: "主页",
    headerLeft: (
      <TouchableOpacity
        onPress={() => {
          // Add a Toast on screen.
          RNToast("暂无消息");
        }}
      >
        <Icon
          style={{ marginLeft: 20 }}
          name="bell-o"
          size={24}
          color="white"
        />
      </TouchableOpacity>
    ),
    headerRight: (
      <TouchableOpacity
        onPress={() => {
          // Add a Toast on screen.
          Linking.openURL(`tel:10086`);
        }}
      >
        <Icon
          style={{ marginRight: 20 }}
          name="phone"
          size={24}
          color="white"
        />
      </TouchableOpacity>
    )
  };

  //   列表引用
  _largeList: any;

  constructor(props: Props) {
    super(props);
    this.state = {
      allLoaded: false,
      list: [],
      srcList: [] // 原始请求数据
    };
  }

  componentDidMount() {
    this._getNetworkData();
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <SearchView
          onSearch={(search: string) => this._startSearch(search)}
          onCancel={() => this.setState({ list: this.state.srcList })}
          searchStore={this.props.searchStore}
        />
        <LargeList
          ref={(ref: any) => (this._largeList = ref)}
          data={this.state.list}
          heightForIndexPath={() => 72}
          renderIndexPath={this._renderItem}
          // 下拉刷新
          refreshHeader={ChineseWithLastDateHeader}
          onRefresh={this._loadData}
          // 上拉加载更多
          loadingFooter={ChineseWithLastDateFooter}
          allLoaded={this.state.allLoaded}
          onLoading={this._loadMore}
        />
      </View>
    );
  }

  _renderItem = ({ section, row }) => {
    const item = this.state.list[section].items[row];
    return (
      <TouchableOpacity onPress={this._gotoDetail}>
        <ListItem
          title={item.name}
          subtitle={item.subtitle}
          leftAvatar={
            <Avatar
              rounded
              source={{ uri: item.avatar_url }}
              avatarStyle={{ borderRadius: 20 }}
              size={40}
            />
          }
          rightIcon={<Icon name="angle-right" size={30} color="#DDDDDD" />}
        />
        <View style={styles.separator} />
      </TouchableOpacity>
    );
  };

  //  空页面
  _createEmptyView = () => {
    return (
      <View
        style={{
          height: "100%",
          justifyContent: "center",
          alignItems: "center"
        }}
      >
        <Text style={{ fontSize: 16 }}>暂无列表数据，下拉刷新</Text>
      </View>
    );
  };

  _loadData = () => {
    this._getNetworkData()
      .then(() => {
        RNToast("下拉刷新成功");
        this._largeList.endRefresh();
      })
      .catch((e: Error) => {
        RNToast(`请求出错了~：${e}`);
        this._largeList.endRefresh();
      });
  };

  _loadMore = () => {
    this._getNetworkData()
      .then(() => {
        RNToast("上拉加载更多成功");
        this._largeList.endLoading();
      })
      .catch((e: Error) => {
        RNToast(`请求出错了~：${e}`);
        this._largeList.endLoading();
      });
  };

  _gotoDetail = () => {
    this.props.navigation.navigate("Detail");
  };

  _startSearch = (search: string) => {
    if (
      search === "" ||
      search.length <= 0 ||
      search === undefined ||
      search === null
    ) {
      this.setState({
        list: this.state.srcList
      });
      return;
    }
    // 模拟本地搜索
    let dataSource: Array<any> = this.state.srcList[0].items;
    let tmpDataSource: Array<any> = [];
    dataSource.forEach((element: any) => {
      if (
        element.name.toLowerCase().indexOf(search.toLowerCase()) >= 0 ||
        element.subtitle.toLowerCase().indexOf(search.toLowerCase()) >= 0
      ) {
        tmpDataSource.push(element);
      }
    });
    this.setState({
      list: [{ items: tmpDataSource }]
    });
  };

  _getNetworkData = () => {
    // 网络请求
    return Network.getRequest("http://localhost:8081/List.json", {})
      .then((response: any) => {
        this.setState({
          list: response.data,
          srcList: response.data
        });
      })
      .catch((e: Error) => {
        RNToast(`请求出错了~：${e}`);
      });
  };
}

const styles = StyleSheet.create({
  separator: {
    height: 0.5,
    backgroundColor: "#EFEFEF"
  }
});
